#!/bin/bash
APP_BASE=$HOME
APP_LOG=$APP_BASE/logs

APP_NAME=''
PORT=''

exist=''
running=''

stop(){
  echo "stop container: $APP_NAME"
  docker stop $APP_NAME
}

clear(){
  echo "clear container and image: $APP_NAME"
  stop

  docker rm $APP_NAME -f
  docker rmi $APP_NAME -f
}

build(){
  echo "build image: $APP_NAME"
  docker build -f Dockerfile -t $APP_NAME:latest .
}

init(){
  echo "init run container: $APP_NAME"

  docker run -d -e TZ=Asia/Shanghai -e SERVER_PORT=$PORT -p $PORT:$PORT --name=$APP_NAME -v /home/raymond/lib:/root/lib -v /home/raymond/logs/$APP_NAME:/root/logs $APP_NAME:latest
}

restart(){
  echo "check container exist & running"

  exist=`docker inspect --format '{{.Id}}' $APP_NAME`
  if [ "${exist}" == "" ]; then
    build
    sleep 1
    init
  fi

  running=`docker inspect --format '{{.State.Running}}' $APP_NAME`
  if [ "${running}" != "true" ]; then
    echo 'restart container: '$APP_NAME
    docker restart $APP_NAME
  fi
}


if [ "$1" = "gateway" ]; then
  APP_NAME="gateway"
  PORT=13000
elif [ "$1" = "admin" ]; then
  APP_NAME="admin"
  PORT=13100
elif [ "$1" = "study" ]; then
  APP_NAME="study"
  PORT=14000
fi
APP_ROOT=$APP_BASE/$APP_NAME

clear
restart
